package com.taichuan.selfcheck.mvp.presenter;


import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.SystemProperties;
import android.text.TextUtils;
import android.util.Log;

import com.orhanobut.logger.Logger;
import com.taichuan.mvp.base.MvpBasePresenter;
import com.taichuan.selfcheck.mvp.viewinterface.AdbControlInterface;
import com.taichuan.selfcheck.mvp.viewinterface.EmptyInterface;
import com.taichuan.tcutils.common.ScriptUtil;
import com.taichuan.tcutils.taichuan.PrintUtils;
import com.taichuan.tcutils.taichuan.SystemUtils;
import com.taichuan.tcutils.taichuan.TcDeviceType;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by CamelLuo on 2018/6/21.
 */
public class AdbControlPresenter extends MvpBasePresenter<AdbControlInterface> {
    private static final String TAG = AdbControlPresenter.class.getSimpleName();

    /**
     * 定义一个方法用于执行传入的adb指令
     */
    public void performAdbCommand(Activity mActivity,String adbCommand){
        if (TextUtils.isEmpty(adbCommand)){
            getView().showAdbPerformResult("执行的adb指令不能为null");
            return;
        }

        Observable
                .just(adbCommand)
                .observeOn(Schedulers.io())
                .map(new Function<String, String>() {
                    @Override
                    public String apply(String command) throws Exception {
                        Logger.t(TAG).e("即将执行的adb指令为：  " + command);
                        //执行adb命令，阻塞方法
                        String result="";
                        if("pm uninstall com.taichuan.u9.dh".equals(command)){
                            if(SystemUtils.isA64()){
                                startLauncher(mActivity);
                                executeCommand(command);
                                result="ok";
                            }else{
                                startLauncher(mActivity);
                                result = ScriptUtil.execRootCmd(command);
                            }
                        }else{
                            if (command .equals("reboot")){
                                PrintUtils.get().printPowerLog("关机");
                            }else if("netcfg".equals(command)){
                                if(SystemUtils.isRk3399() || SystemUtils.isA64()){
                                    command="netstat";
                                }
                            }

                            result = ScriptUtil.execRootCmd(command);
                        }
                        return result;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        //显示执行结果
                        getView().showAdbPerformResult(s);
                        getView().hideLoading();
                    }
                });
    }

    /**
     * 跳转到硬件云平台
     */
    private void startLauncher(Activity mActivity) {
        Intent intent = new Intent("com.taichuan.iot.intent.action.launcher.LAUNCHER");
        intent.setPackage("com.taichuan.hardwarelauncher");
        intent.setData(Uri.parse("hardwareplatform://iot.taichuan.com/reset"));
        mActivity.startActivity(intent);
        Logger.t(TAG).e("执行卸载APK----");
    }

    public String exeMethod(String cmd){
        String result = "";
        DataOutputStream dos = null;
        DataInputStream dis = null;

        try {

            Process p = Runtime.getRuntime().exec("/system/xbin/su");// 经过Root处理的android系统即有su命令
            dos = new DataOutputStream(p.getOutputStream());
            dis = new DataInputStream(p.getInputStream());

            Log.i(TAG, cmd);
            dos.writeBytes(cmd + "\n");
            dos.flush();
            dos.writeBytes("exit\n");
            dos.flush();
            String line = null;
            while ((line = dis.readLine()) != null) {
                Log.d("执行cmd指令结果： ", line);
                result += line + "\n";
            }
            p.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            Logger.t(TAG).e("execRootCmd： 执行cmd指令: " + cmd + "  | 异常：  " + e.getMessage());
            result = "无结果";
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    Logger.t(TAG).e("execRootCmd： 关闭dos异常 : " + cmd + "  | 异常：  " + e.getMessage());
                    result = "无结果";
                }
            }
            if (dis != null) {
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    Logger.t(TAG).e("execRootCmd： 关闭dis异常: " + cmd + "  | 异常：  " + e.getMessage());
                    result = "无结果";
                }
            }
        }
        return result;
    }

    /**
     * 执行脚本命令
     *
     * @param cmd
     */
    private synchronized void executeCommand(String cmd) {
        try {
            // "/data/app/U9Database/setip.sh"
            String dirPath = "/data/app/U9Database";
            File dirFile = new File(dirPath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            // 如果/data/app/U9Database文件夹下存在脚本文件setip.sh则删除
            String filePath = "/data/app/U9Database/setip.sh";
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            } else {
                file.createNewFile();
            }
            // 创建脚本文件
            String filecontext = "#! /system/bin/sh \n" + cmd + "\n";
            OutputStream outstream = new FileOutputStream(file);
            OutputStreamWriter out = new OutputStreamWriter(outstream);
            out.write(filecontext);
            out.flush();
            out.close();
            // 修改Android系统属性使其执行.sh脚本文件
            // 修改.sh脚本文件的属性，加上执行属性
            Runtime.getRuntime().exec("chmod 777 " + dirPath);
            Runtime.getRuntime().exec("chmod 777 " + filePath);
            // 修改Android系统属性去执行脚本文件ifconfig_test.sh
            SystemProperties.set("ctl.stop", "setip");
            Thread.sleep(100);
            SystemProperties.set("ctl.start", "setip");
            Log.d(TAG, "setMac result : " + SystemProperties.get("init.svc.setip", ""));
            Thread.sleep(10);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
